package me.sauce.folkpocket48.data.remote.utils

import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Retrofit
import java.lang.reflect.Type

/**
 * Created by sauce on 2017/7/3.
 *
 */

class ObserveOnMainCallAdapterFactory : CallAdapter.Factory() {
    override fun get(returnType: Type, annotations: Array<Annotation>, retrofit: Retrofit): CallAdapter<Any, Any>? {
        if (getRawType(returnType) != Flowable::class.java) {
            return null // Ignore non-Observable types.
        }

        // Look up the next call adapter which would otherwise be used if this one was not present.

        val delegate = retrofit.nextCallAdapter(this, returnType, annotations)
        return object : CallAdapter<Any, Any> {
            override fun adapt(call: Call<Any>): Any? {
                // Delegate to get the normal Observable...
                val o = (delegate as CallAdapter<Any, Flowable<*>>).adapt(call)
                return o.observeOn(AndroidSchedulers.mainThread())
            }

            override fun responseType(): Type {
                return delegate.responseType()
            }
        }
    }
}

